#用于封装页面操作


import os
from config.path import pic_data_path
from playwright.sync_api import sync_playwright
from utils.decorators import UI_exception_catcher,logger
from config.env import URLDve,Token
from utils.logger import log



class ProblemSolvePage:




    def __init__(self, context):
        try:
            #初始化网页
            self.context = context
            self.context.set_default_timeout(3000)
            self.page = self.context.new_page()
            self.page.goto(URLDve.LLM_problem_solve)
            log.debug("页面打开成功")
        except Exception as e_ini:
            log.error(f"初始化时发送异常:{e_ini}")
            raise e_ini

        try:
            #初始化定位
            #tab
            self.table1 = self.page.get_by_text("解题+讲解")#解题+讲解tab
            self.table2 = self.page.get_by_text("讲解",exact = True)#讲解tab
            self.table3 = self.page.get_by_text("相似题推荐")#相似题推荐tab
            #token输入框
            self.token = self.page.locator("#token")#toke输入框
            #题干输入方式选择框
            self.method_select_box = self.page.locator("span.ant-select-selection-item")#题干输入方式选择框
            self.method_selector = self.page.locator("#methods")#题干输入方式下拉选择框的下拉框
            self.methods = self.page.locator("div.ant-select-item-option-content")#题干输入方式下拉选择框的三个选项
            self.method_selected = self.page.locator("span.ant-select-selection-item")#当前输入方式

            #题干上传区域
            self.text_stem_input = self.page.locator("#input")#题干文本输入框
            self.pic_stem_input = self.page.locator("input[type = 'file']")#题干图片输入框
            self.pic_stem_input2 = self.page.locator(".successWrap--g1hlS")#题干图片输入框——用于判断是否已有图片
            self.pic_stem_input3 = self.page.locator(".ant-upload-list-item-done")#题干图片输入框——用于悬浮
            self.button_enlarge = self.page.get_by_title("Preview file")#放大图片按钮
            self.button_enlarge2 = self.page.locator("div.ant-modal-mask")#放大图片按钮——用于判断是否已经放大
            self.button_enlarge_close = self.page.locator("button.ant-modal-close")#关闭放大的图片按钮
            self.button_remove = self.page.get_by_title("Remove file")#删除图片按钮
            self.input_url = self.page.locator("#imgUrl")#题干图片url输入框

            #清空输入与提交按钮
            self.clear_button = self.page.get_by_role(role = "button",name = "清空输入")#清空按钮
            self.submit_button = self.page.locator("[type = 'submit']")#提交按钮

            #
            self.title = self.page.locator(".title--bWsup")#解析标题——用于判断是否成功生成解析

            self.rid = self.page.locator(".ridWrap--7V9im").locator("[type = 'text']")#rid输入框
            self.task_id = self.page.locator(".taskIdWrao--KFXWz").locator("[type = 'text']")#task_id输入框

            self.step = self.page.locator(".stepIcon--l0wif")#听步骤讲解




        except Exception as e_loc:
            log.error(f"元素定位时发送异常:{e_loc}")
            raise e_loc


    #点击“解题+讲解”tab
    @logger
    @UI_exception_catcher
    def tab1_click(self):
        return self.table1.click()

    #点击讲解tab
    @logger
    @UI_exception_catcher
    def tab2_click(self):
        return self.table2.click()

    #点击相似题推荐tab
    @logger
    @UI_exception_catcher
    def tab3_click(self):
        return self.table3.click()

    #输入token
    @logger
    @UI_exception_catcher
    def token_input(self, token:str):
        return self.token.fill(token)

    #获取token输入框中的内容
    @logger
    @UI_exception_catcher
    def token_get_content(self):
        return self.token_input.input_value()

    #点击展开下拉选择框
    @logger
    @UI_exception_catcher
    def method_click(self):
        return self.method_select_box.click()

    #判断下拉选择框是否展开
    @logger
    @UI_exception_catcher
    def method_is_expend(self):
        return self.method_selector.get_attribute("aria-expanded") == "true"

    #获取当前题干输入方式
    @logger
    @UI_exception_catcher
    def method_get_selected(self):
        return self.method_select_box.text_content()

    #选择题干输入方式
    @logger
    @UI_exception_catcher
    def method_select(self, method:int):
        """
        1表示题干文本方式
        2表示题干图片
        3表示题干图片url
        """
        if not self.method_is_expend():
            self.method_click()
        return self.methods.nth(method - 1).click()

    #获取当前输入框中的内容
    @logger
    @UI_exception_catcher
    def text_get_content(self):
        return self.text_stem_input.input_value()

    #向输入框内输入文本题干
    @logger
    @UI_exception_catcher
    def text_input(self, content:str):
        if not self.method_get_selected() == "题干文本":
            self.method_select(1)
        return self.text_stem_input.fill(content)

    #向输入框输入图片题干
    @logger
    @UI_exception_catcher
    def pic_input(self,file_name:str):
        if not self.method_get_selected() == "题干图片":
            self.method_select(2)
        return self.page.set_input_files("input[type = 'file']", os.path.join(pic_data_path, file_name))


    #放大已上传的图片
    @logger
    @UI_exception_catcher
    def pic_enlarge(self):
        self.pic_stem_input.wait_for(state = "attached")
        self.pic_stem_input3.hover()
        return self.button_enlarge.click()


    #关闭放大的图片
    @logger
    @UI_exception_catcher
    def pic_enlarge_close(self):
        if  self.button_enlarge2.count() == 0:
            log.error("关闭放大图片失败，请先放大图片")
            return False
        return self.button_enlarge_close.click()


    #删除已上传的图片
    @logger
    @UI_exception_catcher
    def pic_remove(self):
        if self.pic_stem_input.count() == 0:
            log.error("删除图片失败，请先上传图片")
            return False
        page.page.locator(".ant-upload-list-item-done").hover()
        return self.button_remove.click()

    #输入图片url
    @logger
    @UI_exception_catcher
    def url_input(self,pic_url:str):
        if not self.method_get_selected() == "题干图片url":
            self.method_select(3)
        self.input_url.fill(pic_url)
        log.debug(f"图片url输入框当前内容:{self.input_url.input_value()}")
        return True

    #点击清空输入按钮
    @logger
    @UI_exception_catcher
    def clear_click(self):
        if not self.clear_button.is_enabled():
            log.error("清空输入按钮不可点击，请先输入必须内容")
            return False
        return self.clear_button.click()

    #点击提交输入框
    @logger
    @UI_exception_catcher
    def submit_click(self):
        return self.submit_button.click()

    #获取rid
    @logger
    @UI_exception_catcher
    def get_rid(self):
        return self.rid.input_value()

    #获取task_id
    @logger
    @UI_exception_catcher
    def get_task_id(self):
        self.title.wait_for(state="attached", timeout=20000)
        return self.task_id.input_value()

    #判断是否解题成功
    @logger
    @UI_exception_catcher
    def is_success(self):
        try:
            self.title.wait_for(state="attached", timeout=60000)
            return True
        except Exception as e_loc:
            return False


    #进入步骤讲解
    @logger
    @UI_exception_catcher
    def goto_step(self):
        return self.step.click(timeout = 30000)









if __name__ == "__main__":
    #初始化浏览器
    playwright = sync_playwright().start()
    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context()
    log.debug("浏览器启动成功")

    #打开页面
    page = ProblemSolvePage(context)

    #执行需要调试的操作

    page.token_input(Token.token_11_9)
    page.text_input("1+1")
    page.submit_click()
    log.info(page.get_task_id())
    page.is_success()
    page.page.wait_for_timeout(1000)


    #关闭浏览器
    context.close()
    browser.close()
    playwright.stop()
    log.debug("浏览器关闭成功")




